package com.cy.sys.service.realm;

import java.util.HashSet;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.cy.sys.dao.SysMenuDao;
import com.cy.sys.dao.SysUserDao;
import com.cy.sys.pojo.SysUser;



public class SysUserRealm extends AuthorizingRealm{
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysMenuDao sysMenuDao;
	
	/** 配置授权 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//1.获取用户
		SysUser user = (SysUser)principals.getPrimaryPrincipal();
		//2.获取此用户对应的权限
		List<String> permission = sysMenuDao.selectPermisssionByUserId(user.getId());
		if(permission==null)
			throw new AuthorizationException();
		HashSet<String> permissions = new HashSet<>();
		for (String string : permission) {
			if(!StringUtils.isEmpty(string)) {
				permissions.add(string);
			}
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(permissions);
		return info;
	}

	/** 配置身份验证 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken)token;
		String username = upToken.getUsername();
		SysUser user = sysUserDao.fondUserByUserName(username);
		if(user==null)
			throw new UnknownAccountException();
		if(user.getValid()!=1)
			throw new IncorrectCredentialsException();
		ByteSource salt = ByteSource.Util.bytes(user.getSalt());
		SimpleAuthenticationInfo authentication = new SimpleAuthenticationInfo(
							user, 
							user.getPassword(), 
							salt, 
							getName());
		return authentication;
	}
	
	@Override
	public CredentialsMatcher getCredentialsMatcher() {
		HashedCredentialsMatcher cManager = new HashedCredentialsMatcher();
		cManager.setHashAlgorithmName("MD5");
		cManager.setHashIterations(1);
		return cManager;
	}
	

}
